"use client";
import { useNotifications } from "@/app/hooks/notification.hook";
import ordersService from "@/app/services/orders.service";
import Modal from "@/components/modal/modal";
import CustomSelect from "@/components/select/select";
import { formatDateToCustom } from "@/lib/date";
import Order, { OrderStatus } from "@/shared/order";
import User from "@/shared/user";
import { useEffect, useState } from "react";

export default function OrdersPage() {
  const { showError, showSuccess } = useNotifications();
  const [loading, setLoading] = useState(true);
  const [orders, setOrders] = useState<(Order & { user: User })[]>([]);
  const [lastClicked, setLastClicked] = useState<number>(0);
  const [isOpen, setIsOpen] = useState(false);

  const openModal = () => setIsOpen(true);
  const closeModal = () => setIsOpen(false);
  useEffect(() => {
    const l = async () => {
      const orders = await ordersService.getAllItems();
      setOrders(orders);
      setLoading(false);
    };

    l();
  }, []);

  const namedStatus = (status: string) => {
    switch (status) {
      case "PROCESSING":
        return "В обработке";
      case "PREPARING":
        return "Сбор";
      case "DELIVERY":
        return "Передан в доставку";
      case "COMPLETED":
        return "Завершен";
    }
  };

  const handleChangeStatus = async (orderId: number, id: number) => {
    let status: string;
    switch (id) {
      case 0:
        status = "PROCESSING";
        break;
      case 1:
        status = "PREPARING";
        break;
      case 2:
        status = "DELIVERY";
        break;
      case 3:
        status = "COMPLETED";
        break;
      default:
        return;
    }

    try {
      await ordersService.changeOrderStatus(orderId, status);
      showSuccess(`Статус заказа №${orderId} успешно изменен`);
    } catch (e) {
      showError(`Невозможно изменить статус`);
    }
  };

  if (loading)
    return (
      <section style={{ display: "flex", flex: 2, width: "100%" }}>
        <span style={{ margin: "0 auto" }} className="loader"></span>
      </section>
    );

  return (
    <section className="me" style={{ flex: 2 }}>
      <h1 className="heading">
        <span>Заказы</span>
      </h1>
      <div className="column">
        <table className="ordersTable">
          <thead>
            <tr>
              <th>№</th>
              <th>Статус</th>
              <th>Дата заказа</th>
              <th>Адрес</th>
              <th>Кол-во позиций</th>
              <th>Сумма</th>
              <th>Кол-во персон</th>
              <th>Описание</th>
              <th>Позиции</th>
              <th>Номер телефона</th>
            </tr>
          </thead>
          <tbody>
            {orders.map((o) => (
              <tr>
                <td>{o.id}</td>
                <td>
                  <CustomSelect
                    placeholder={namedStatus(o.status.toString())}
                    options={[
                      { label: "В обработке", value: 0 },
                      { label: "Сбор", value: 1 },
                      { label: "Передан в доставку", value: 4 },
                      { label: "Завершен", value: 3 },
                    ]}
                    onChange={(val) => {
                      handleChangeStatus(o.id, val);
                    }}
                  />
                </td>
                <td>{formatDateToCustom(new Date(o.createdAt))}</td>
                <td>{o.address}</td>
                <td>{o.productCount}</td>
                <td>{o.sum} руб.</td>
                <td>{o.count}</td>
                <td>{o.description}</td>
                <td style={{ textAlign: "center" }}>
                  <span
                    onClick={() => {
                      setLastClicked(o.id);
                      openModal();
                    }}
                    style={{ cursor: "pointer", fontSize: "25px" }}
                    className="fa fa-cutlery"
                  ></span>
                </td>
                <td>{o.user.phone}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {isOpen && <Modal orderId={lastClicked} onClose={closeModal} />}
    </section>
  );
}
